<template>
    <view class="detail">
        <SRV-topbar title="购物车"></SRV-topbar>
        <scroll-view scroll-y="true" class="shoppingCart">
            <view class="main" v-if="info.length > 0">
                <view class="top">
                    <view class="left"><text></text></view>
                    <view class="right" @click="getedit()">
                        <image :src="'https://hdsq.aoorange.cn/attachment/xcx/icon/bianji.png'" mode="aspectFill"></image>
                        <text>{{isedit?'完成':'编辑'}}</text>
                    </view>
                </view>
                <view class="content" v-for="(store,index) in info" :key="index">
                    <view class="contop">
                        <view :class="selStore[index]?'sel':'nosel'" @click="selStoreFun(index)"></view>
                        <image :src="store.logo" mode="widthFix"></image>
                        <text @click="jump('store_home', store.id)">{{store.title}}</text>
                    </view>
                    <view v-if="store.remark != ''">{{store.remark}}</view>
                    <uni-swipe-action v-for="(item,index1) in store.productList" :key="index1">
                        <uni-swipe-action-item :options="options" @click="delItem(index, index1)" @change="change">
                            <view class='cont'>
                                <view class="left">
                                    <view :class="selList[index][index1]?'sel':'nosel'" @tap.stop="selProduct($event, index, index1)"></view>
                                    <image :src="item.product_img" mode="aspectFill"  @click="jump(item.jumpType, item.jumpLink)"></image>
                                </view>
                                <view class="right"  @click="jump(item.jumpType, item.jumpLink)">
                                    <view class="productName">{{item.product_name}}</view>
                                    <text class="skuName">{{item.sku_name}}</text>
                                    <view class="productPrice">
                                        <text class="price">￥{{item.showPrice}}</text>
                                        <text class="oneline" v-if="item.market_price > 0">￥{{item.market_price}}</text>
                                    </view>
                                    <view class="uni-numbox">
                                        <view class="uni-numbox-minus"  @tap.stop="_calcValue($event, 'subtract', index, index1)">-</view>  
                                        <input class="uni-numbox-value" type="number" :value="item.number"  :data-id="item.id" disabled="true">  
                                        <view class="uni-numbox-plus" :class="item.sku_stock > item.number ? '' : 'uni-numbox-disabled'" @tap.stop="_calcValue($event, 'add', index, index1)">+</view>
                                    </view>  
                                </view>
                            </view>
                            <view style="padding: 20rpx;border: 1rpx #EBECF0 solid;width: 100%;" v-if="item.numActivity != ''">{{item.numActivity}}</view>
                        </uni-swipe-action-item>
                    </uni-swipe-action>
                    
                </view>
                <view class="bottom">
                    <view class="left">
                        <view :class="allsel?'sel':'nosel'" @click="allSelFun()"></view>
                        <text>全选</text>
                    </view>
                    <view class="right">
                        <view v-if="isedit" class="del" @click="delAll()">
                            删除
                        </view>
                        <view v-if="!isedit" class="text">
                            <view class="all">
                                <text>合计</text>
                                <text>￥{{selTotalMoney}}</text>
                            </view>
                            <view class="freight">不含运费</view>
                        </view>
                        <text v-if="!isedit" class="pay" @click="confirmOrder()">结算({{selTotalNum}})</text>
                    </view>
                </view>

            </view>
            <view v-if="info.length == 0" class="noshoppingCart">
                <image :src="'https://hdsq.aoorange.cn/attachment/xcx/icon/nocar.png'" mode="aspectFill"></image>
                <text>
                    暂未有商品加入购物车～
                </text>
            </view>
        </scroll-view>
    </view>
</template>

<script>
    var _self;
	import serve from '../../static/request.js';
	import common from '../../static/jump.js';
	export default {
		data() {
			return {
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#EB5938',
						color: "#ffffff"
					}
				}],
				list: [],
				allsel: false,
				isedit: false,
				
				info: {},
				cartNumList: [],
				selStore: [],
				selList: [],
				selTotalNum: 0,
				selTotalMoney : 0,
				selTotalPoint : 0,
			}
		},
		methods: {
            numFilter (value) {
            	// 截取当前数据到小数点后三位
            	let tempVal = parseFloat(value).toFixed(3)
            	let realVal = tempVal.substring(0, tempVal.length - 1)
            	return realVal
            },
			delItem(mk, sk) {
				let merchantItem = _self.info[mk];
				let skuItem = merchantItem.productList[sk];
				uni.showModal({
				    title: '提示',
				    content: '您确定删除该产品吗',
				    success: function (res) {
				        if (res.confirm) {
				            serve.request({
                                url: '/store/cart/delete-ids',
                                data:{
                                    appkey: uni.getStorageSync('appkey'),
                                    'access-token': uni.getStorageSync('access-token'),
                                    cartIds:skuItem.id,
                                },
                                v: '/v2',
                            }).then(res => {
                                uni.showToast({
                                    title: res.message,
                                    icon : 'none'
                                });
                                if(res.code == 200) {
                                    merchantItem.productList.splice(sk, 1);
                                    if(_self.selList[mk][sk]) {
                                        _self.selList[mk][sk] = false;
                                    }
                                    if(merchantItem.productList.length == 0) {
                                        _self.info.splice(mk, 1);
                                        if(_self.selStore[mk]) {
                                            _self.selStore[mk] = false;
                                        }
                                    } else {
                                        let state = false;
                                        merchantItem.productList.forEach((item,key) => {
                                        	if(_self.selList[mk][key]) {
                                        		state = true;
                                        	} 
                                        });
                                        _self.selStore[mk] = state;
                                    }
                                    _self.$forceUpdate();
                                    _self.totalSelFun();
                                } 
                            });
				        } 
				    }
				});
			},
			delAll(){
				if(_self.selTotalNum == 0) {
					uni.showToast({
						title: "请选择要删除的产品",
						icon: 'none'
					});
					return ;
				}
				let skuIds = '';
				_self.info.forEach((storeItem, key)=> {
					storeItem.productList.forEach((item,key1) => {
						if(_self.selList[key1]) {
							skuIds += item.id + ',';
						} 
					});
				});
				uni.showModal({
				    title: '提示',
				    content: '您确定删除选择的产品吗',
				    success: function (res) {
				        if (res.confirm) {
				            serve.request({
                                url: '/store/cart/delete-ids',
                                data:{
                                    appkey: uni.getStorageSync('appkey'),
                                    'access-token': uni.getStorageSync('access-token'),
                                    cartIds:skuIds,
                                },
                                v: '/v2',
                            }).then(res => {
                                uni.showToast({
                                    title: res.message,
                                    icon : 'none'
                                });
                                if(res.code == 200) {
                                    _self.getInfo();
                                }
                            });
				        } 
				    }
				});
			},
			confirmOrder() {
				if(_self.selTotalNum == 0) {
					uni.showToast({
						title: "请选择要提交订单的产品",
						icon: 'none'
					});
					return ;
				}
				let cartIds = '';
				_self.info.forEach((storeItem, key)=> {
					storeItem.productList.forEach((item,key1) => {
						if(_self.selList[key][key1]) {
							cartIds += item.id + ',';
						} 
					});
				});
				_self.jump('addOrder', 'type=cart&data='+cartIds);
			},
			change(open) {
				console.log('当前开启状态：' + open)
			},
			selStoreFun(index) {
				let state = true;
				if(_self.selStore[index]) {
					_self.selStore[index] = false;
					state = false;
				} else {
					_self.selStore[index] = true;
				}
				let productList = _self.info[index].productList;
				productList.forEach((item, index1) => {
					_self.selList[index][index1] = state;
				});
				_self.$forceUpdate();
				_self.totalSelFun();
			},
			selProduct(e, mk, sk) {
                e.preventDefault();
				if(_self.selList[mk][sk]) {
					_self.selList[mk][sk] = false;
				} else {
					_self.selList[mk][sk] = true;
				}
				let state = false;
				let productList = _self.info[mk].productList;
				productList.forEach((item, index1) => {
					if(_self.selList[mk][index1]){
						state = true;
					}
				});
				_self.selStore[mk] = state;
				_self.$forceUpdate();
				_self.totalSelFun();
			},
			allSelFun() {
				this.allsel = !this.allsel;
				this.info.forEach((storeItem, key)=> {
					this.selStore[key] = this.allsel;
					storeItem.productList.forEach((item,key2) => {
						this.selList[key][key2] = this.allsel;
					})
				});
				_self.$forceUpdate();
				_self.totalSelFun();
			},
			totalSelFun() {
				let isAllSel = true;
				let totalMoney = 0;
				let totalNum = 0;
				_self.info.forEach((storeItem, key)=> {
					storeItem.productList.forEach((item,key1) => {
						if(_self.selList[key][key1]) {
							totalNum ++;
							let productNum = item.number;
							totalMoney = _self.numFilter(Number(totalMoney) + Number(productNum * item.showPrice));
						} else {
							isAllSel = false;
						}
					});
				});
				_self.allsel = isAllSel;
				_self.selTotalMoney = _self.numFilter(totalMoney);
				_self.selTotalNum = totalNum;
				_self.$forceUpdate();
			},
			getedit() {
				this.isedit = !this.isedit
			},			
			_calcValue(e, type, mk, sk) {
                e.preventDefault();
                let merchantItem = _self.info[mk];
                let skuItem = merchantItem.productList[sk];
				let value = skuItem.number;  
				let step = 1;  
				let min = 1;
				let max = skuItem.sku_stock;
				if (type === 'subtract') {  
					value -= step  
				} else if (type === 'add') {  
					value = parseInt(Number(value) + Number(step))
				}  
				if (value > max) {  
					return  
				}
                if(value < min) {
                    _self.delItem(mk, sk);
                    return ;
                }
                var totalMoney = 0;
                var nowBenefits = 0;
                var nowSubsidy = 0;
                if(value == 1) {
                    totalMoney = skuItem.userPriceInfo.one;
                    nowBenefits = skuItem.benefits.one;
                    nowSubsidy = skuItem.subsidy.one;
                } else if (value == 2) {
                    totalMoney = Number(skuItem.userPriceInfo.one) + Number(skuItem.userPriceInfo.two);
                    nowBenefits = Number(skuItem.benefits.one) + Number(skuItem.benefits.two);
                    nowSubsidy = Number(skuItem.subsidy.one) + Number(skuItem.subsidy.two);
                } else if (value == 3) {
                    totalMoney = Number(skuItem.userPriceInfo.one) + Number(skuItem.userPriceInfo.two) + Number(skuItem.userPriceInfo.three);
                    nowBenefits = Number(skuItem.benefits.one) + Number(skuItem.benefits.two) + Number(skuItem.benefits.three);
                    nowSubsidy = Number(skuItem.subsidy.one) + Number(skuItem.subsidy.two) + Number(skuItem.subsidy.three);
                } else {
                    let bs = Math.floor(value / 3);
                    let ys = value % 3;
                    let tm1 = Number(skuItem.userPriceInfo.one);
                    let tm2 = Number(skuItem.userPriceInfo.one) + Number(skuItem.userPriceInfo.two);
                    let tm3 = Number(skuItem.userPriceInfo.one) + Number(skuItem.userPriceInfo.two) + Number(skuItem.userPriceInfo.three);
                    let tb1 = Number(skuItem.benefits.one);
                    let tb2 = Number(skuItem.benefits.one) + Number(skuItem.benefits.two);
                    let tb3 = Number(skuItem.benefits.one) + Number(skuItem.benefits.two) + Number(skuItem.benefits.three);
                    let sb1 = Number(skuItem.subsidy.one);
                    let sb2 = Number(skuItem.subsidy.one) + Number(skuItem.subsidy.two);
                    let sb3 = Number(skuItem.subsidy.one) + Number(skuItem.subsidy.two) + Number(skuItem.subsidy.three);
                    totalMoney = tm3 * bs + (ys == 1 ? tm1 : ys == 2 ? tm2 : 0);
                    nowBenefits = tb3 * bs + (ys == 1 ? tb1 : ys == 2 ? tb2 : 0);
                    nowSubsidy = sb3 * bs + (ys == 1 ? sb1 : ys == 2 ? sb2 : 0);
                }
                skuItem.showPrice = Number(totalMoney) / Number(value);
                console.info(totalMoney + " / " + value + " = "+skuItem.showPrice);
                skuItem.showPrice = this.numFilter(skuItem.showPrice);
				serve.request({
                    url: '/store/cart/edit',
                    data: {
                        appkey: uni.getStorageSync('appkey'),
                        'access-token': uni.getStorageSync('access-token'),
                        cartId: skuItem.id,
                        num: value,
                    },
                    v: '/v2'
                }).then(res => {
                    uni.showToast({
                        title: res.message,
                        icon : 'none'
                    });
                    if(res.code == 200) {
                        skuItem.number = value;
                        _self.$forceUpdate();
                        _self.totalSelFun();
                    }
                });
			},
			getInfo() {
                uni.showLoading({
                    title: '加载中',
                    mask: true
                });
				serve.request({
                    url: '/store/cart/list',
                    data: {
                        appkey: uni.getStorageSync('appkey'),
                        'access-token': uni.getStorageSync('access-token'),
                    },
                    v: '/v2',
                }).then(res => {
                    uni.hideLoading();
                    _self.info = res.data;
                    _self.allsel = false;
                    _self.selStore = [];
                    _self.selList = [];
                    _self.info.forEach((storeItem, key)=> {
                        _self.selStore[key] = false;
                        _self.selList[key] = [];
                    	storeItem.productList.forEach((item,key1) => {
                    		_self.selList[key][key1] = false;
                    	});
                    });
                    _self.$forceUpdate;
                });
			},
			jump(jump_type, jump_link){
				common.jump(jump_type, jump_link);
			},
		},
		onLoad() {
            _self = this;
			if(uni.getStorageSync('access-token') == '') {
				common.jump('login');
				return ;
			}
		},
		onShow() {
            _self.allsel = false;
            _self.selStore = [];
            _self.selList = [];
			_self.getInfo();
		},
		onPullDownRefresh() {
			_self.getInfo();
		}
	}
</script>

<style scoped lang="scss">
	@media only screen and (device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3) {
		    .main {
		        padding-bottom: 224rpx !important;
				.bottom{
					 padding-bottom: 12px !important;
				}
		    }
		}
	.shoppingCart {
		max-height: 100vh;
        .noshoppingCart{
			width: 100%;
			min-height: 80vh;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			image{
				width: 128rpx;
				height: 116rpx;
			}
			text{
				font-size:28rpx;
				color:rgba(204,204,204,1);
				margin-top: 38rpx;
			};
		}
		.main {
			width: 100%;
			padding-bottom: 200rpx;

			.top {
				display: flex;
				padding: 20rpx 30rpx;
				box-sizing: border-box;
				justify-content: space-between;
				align-items: center;
				color: #666666;
				border-bottom: 1rpx rgba(235, 236, 240, 1) solid;
				.left {
					font-size: 32rpx;
					display: flex;
					align-items: center;
					image {
						width: 35rpx;
						height: 33rpx;
						margin-right: 13rpx;
					}
					text {
						position: relative;
						padding-right: 30rpx;
					}
				}
				.right {
					font-size: 32rpx;
					display: flex;
					align-items: center;
					image {
						width: 27rpx;
						height: 33rpx;
						margin-right: 20rpx;
					}
				}
			}
			.content{
				.contop{
					display: flex;
					align-items: center;
					box-sizing: border-box;
				    padding-left: 30rpx;
					height: 100rpx;
					border-bottom: 1rpx #EBECF0 solid;
					image {
						width:40rpx;
						height:35rpx;
						margin-left: 10rpx;
					}
									
					.sel {
						background-image: url(https://hdsq.aoorange.cn/attachment/xcx/icon/xuanzhong.png);
						background-repeat: no-repeat;
						width: 40rpx;
						height: 40rpx;
						background-size: 100%;
					}
									
					.nosel {
						width: 36rpx;
						height: 36rpx;
						border: 1rpx solid #999999;
						border-radius: 50%;
					}
					text{
						color: #333333;
						font-size: 28rpx;
						margin-left: 10rpx;
					}
				}
				.cont {
					width: 100%;
					display: flex;
					align-items: center;
					box-sizing: border-box;
					padding: 20rpx 30rpx;
					border-bottom: 1rpx #EBECF0 solid;			
					.left {
						display: flex;
						align-items: center;
				
						image {
							width: 170rpx;
							height: 170rpx;
							margin-left: 20rpx;
						}
				
						.sel {
							background-image: url(https://hdsq.aoorange.cn/attachment/xcx/icon/xuanzhong.png);
							background-repeat: no-repeat;
							width: 40rpx;
							height: 40rpx;
							background-size: 100%;
						}
				
						.nosel {
							width: 36rpx;
							height: 36rpx;
							border: 1rpx solid #999999;
							border-radius: 50%;
						}
					}
				
					.right {
						width: 440rpx;
						height: 100%;
						position: relative;
						display: flex;
						flex-direction: column;
						justify-content: space-between;
						padding: 0 10rpx;
                        .productName {
                            font-size: 32rpx;
							font-weight: bold;
                            text-overflow: -o-ellipsis-lastline;
                            overflow: hidden;
                            text-overflow: ellipsis;
                            display: -webkit-box;
                            -webkit-line-clamp: 2;
                            line-clamp: 2;
                            -webkit-box-orient: vertical;
                            white-space:unset;
                            word-break: break-all;
                        }
                        .skuName {
                            font-size: 24rpx;
                            color: #FF0000;
                        }
                        .productPrice {
                            display: flex;
                            align-items: center;
                        }
						.price{
							color: #FFBC00;
							font-size: 26rpx;
						}
						.oneline {
							font-size: 20rpx;
							color: #999999;
                            margin-left: 10rpx;
							text-decoration: line-through;
						}
						.uni-numbox {
							display: flex;  
							flex-direction: row;  
							align-items: center;
							position: absolute;
							justify-content: flex-start;  
							background: rgba(255, 255, 255, 1);
							border: 1rpx solid #CCCCCC;
							border-radius: 32rpx;
							height: 50rpx;  
							overflow: hidden;
							bottom: 0rpx;
							right: 0rpx;
						}  
						.uni-numbox-minus,  
						.uni-numbox-plus {  
							margin: 0;  
							background-color: #FFFFFF;  
							width: 50rpx;  
							height: 100%;  
							line-height: 50rpx;  
							text-align: center;  
							color: #555555;  
						}  
						.uni-numbox-minus {  
							border-right: none;  
							border-top-left-radius: 32rpx;  
							border-bottom-left-radius: 32rpx;  
						}  
						.uni-numbox-plus {  
							border-left: none;  
							border-top-right-radius: 32rpx;  
							border-bottom-right-radius: 32rpx;  
						}  
						.uni-numbox-value {  
							border: 1rpx solid rgba(60,72,104,0.06);
							background-color: #ffffff;  
							width: 50rpx;  
							height: 100%;  
							text-align: center;  
						}  	
						.uni-numbox-disabled {  
							color: #c0c0c0;  
						} 
					}
				}
			}
			

			.bottom {
				// padding-bottom: env(safe-area-inset-bottom);
				border-top: 1rpx #EBECF0 solid;
				position: fixed;
				bottom: 20rpx;
				background: #FFFFFF;
				box-sizing: border-box;
				padding-left: 30rpx;
				display: flex;
				align-items: center;
				width: 100%;
				height: 100rpx;
				box-shadow: 0px 1rpx 0px 0px rgba(235, 236, 240, 1);
				justify-content: space-between;

				.left {
					display: flex;
					align-items: center;
					font-size: 28rpx;

					.sel {
						background-image: url(https://hdsq.aoorange.cn/attachment/xcx/icon/xuanzhong.png);
						background-repeat: no-repeat;
						width: 40rpx;
						height: 40rpx;
						background-size: 100%;
						margin-right: 20rpx;
					}

					.nosel {
						width: 36rpx;
						height: 36rpx;
						border: 1rpx solid #999999;
						border-radius: 50%;
						margin-right: 20rpx;
					}
				}

				.right {
					display: flex;
					height: 100%;

					.del {
						width: 240rpx;
						height: 72rpx;
						background: rgba(255,188,0,0.1);;
						color: #FFBC00;
						border-radius: 36rpx;
						text-align: center;
						margin-top: 17rpx;
						margin-right: 70rpx;
						text-align: center;
						line-height: 72rpx;
						font-size: 28rpx;
					}

					.text {
						display: flex;
						justify-content: center;
						align-items: flex-end;
						padding-right: 15rpx;
						flex-direction: column;

						.all {
							font-size: 20rpx;
							color: rgba(60, 72, 104, 0.5);

							text:last-child {
								margin-left: 10rpx;
								font-size: 28rpx;
								font-weight: bold;
								color: #FF5F60;
							}
						}

						.freight {
							font-size: 20rpx;
							color: rgba(60, 72, 104, 0.5);
						}
					}

					.pay {
						width: 240rpx;
						height: 100%;
						background: rgba(235, 89, 56, 1);
						text-align: center;
						line-height: 100rpx;
						font-size: 28rpx;
						color: #FFFFFF;
						font-weight: bold;
					}
				}
			}

		}
	}
</style>
